package com.itheima.core;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.factory.MapperFactory;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;


public class BaseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    /*
        http://localhost:8080/虚拟路径/DogServlet?method=eat
        http://localhost:8080/虚拟路径/DogServlet/eat
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");

            /*1.获取要访问的方法的名字*/
            String uri = request.getRequestURI();
            String methodName = uri.substring(uri.lastIndexOf("/")+1);

            /*2.通过反射执行方法*/
            Class clazz = this.getClass();
            Method method = clazz.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            Object result = method.invoke(this,request,response);

            /*3.判断方法上有没有ResponseBody注解，如果有，就将方法的返回值变成JSON写给浏览器*/
            if(method.getDeclaredAnnotation(ResponseBody.class) != null){
                response.setContentType("application/json;charset=utf-8");
                String json = new ObjectMapper().writeValueAsString(result);
                response.getWriter().println(json);
                return;
            }

            /*3.判断方法有没有返回值，如果有返回值判断重定向还是转发*/
            if(result != null){
                if(result instanceof String){//判断是否是String类型 避免下一行强转时报类型转换异常
                    String r = (String)result;
                    if(r.startsWith("forward:")){
                        request.getRequestDispatcher("/"+r.substring(8)).forward(request,response);
                    }else if(r.startsWith("redirect:")){
                        response.sendRedirect(request.getContextPath()+"/"+r.substring(9));
                    }else{
                        request.getRequestDispatcher("/"+r).forward(request,response);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println("服务器停电了,请稍候再来访问");


            SqlSession sqlSession = MapperFactory.tl.get();

            if(sqlSession!=null){
                sqlSession.close();
            }
        }finally {

        }
    }

}
